﻿using System;
using System.Windows.Forms;
using QAToolsAddin.Components;
using Excel = Microsoft.Office.Interop.Excel;

namespace QAToolsAddin.GenericDialogs.Fields {

    public class FieldRange : Field, IField {
        readonly ExcelRefEdit _control;

        public override event EventHandler KeyReturn {
            add { _control.KeyReturn += delegate { value.Invoke(this, null); }; }
            remove { _control.KeyReturn += delegate { value.Invoke(this, null); }; }
        }

        public FieldRange(string name, string info, Excel.Range value, bool retore = false)
            : base(name, info, retore) {
            _control = new ExcelRefEdit {
                AllowTextInput = false,
                DisplayMode = ExcelRefEdit.XlMode.AddressRelative
            };
            _control.Range = value;
        }

        public override Control Control {
            get { return _control; }
        }

        public Excel.Range Value {
            get {
                string errorMessage;
                if (Validate(out errorMessage))
                    return _control.Range;
                throw new Exception(errorMessage);
            }
            set {
                _control.Range = value;
            }
        }

        object IField.Value {
            get { return Value; }
            set { Value = (Excel.Range)value; }
        }

        public override bool Validate(out string errorMessage) {
            errorMessage = null;
            if (_control.Range == null)
                errorMessage = "Invalide selection";
            else return true;
            _control.SelectAll();
            return false;
        }

    }

}